<!-- 账号列表 -->
<template>
  <div id="AccountList">
    <div class="box">
      <div class="box_header">
        <div>账号列表</div>
        <div>
          <el-button type="success">导入</el-button>
          <el-button type="primary">导出</el-button>
        </div>
      </div>
      <div class="box_body">
        <!-- 列表 -->
        <el-table :data="currentOrders" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" v-model="msg" />
          <el-table-column property="account" label="账号" width="120" />
          <el-table-column property="userGroup" label="用户组" width="120" />
          <el-table-column property="ctime" label="创建时间" width="650" />
          <el-table-column property="canDo" label="操作" width="435">
            <template #default="scoped">
              <el-button @click="handleEdit(scoped.row.id)">编辑</el-button>
              <el-button type="danger" @click="openOne(scoped.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 翻页 -->
        <div class="demo-pagination-block pageBox">
          <!-- <div class="demonstration">All combined</div> -->
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5]" :size="size"
            layout="total, sizes, prev, pager, next, jumper" :total="tableData.length" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
        <br>
        <!-- 批量删除 -->
        <div>
          <el-button type="danger" @click="openTwo">批量删除</el-button>
          <el-button type="primary" @click="handleCanle">取消选择</el-button>
        </div>
        <!-- 编辑页面 -->
        <div class="edit_box" v-show="msgTwo">
          <div class="edit_box_header">
            <div>账号编辑</div>
            <div class="close" @click="handleClose">X</div>
          </div>
          <div class="edit_box_body">
            <div>
              <span>&emsp;账号</span>
              &nbsp;
              <el-input v-model="inputName" style="width: 20vw;" placeholder="请输入账号名称" class="inpName" />
            </div>
            <div>
              <span>用户组</span>
              &nbsp;
              <select name="" id="" class="selectBox" @change="inutSelect()" v-model="selectedUserGroup">
                <option value="普通管理员">普通管理员</option>
                <option value="超级管理员">超级管理员</option>
              </select>
            </div>
          </div>
          <div class="edit_box_foot">
            <div class="edit_box_foot_btn_box">
              <el-button class="btn" @click="handleClose">取消</el-button>
              <el-button type="primary" class="btn" @click="handleFinsihEdit">确定</el-button>
            </div>
          </div>
        </div>
        <!-- 蒙版 -->
        <div class="mask" v-show="msgTwo"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue';
//引入账号列表接口
import { fetchLoginSixteen } from '../../api/index';
//引入账号批量删除
import { fetchLoginSeventeen } from '../../api/index';
//引入账号修改
import { fetchLoginEighten } from '../../api/index';
//引入账号单个删除
import { fetchLoginNineteen } from '../../api/index';

import { ElMessage, ElMessageBox } from 'element-plus'
import { ComponentSize } from 'element-plus';

//编辑下拉框
const inputName = ref('');//长哈名称
const selectedUserGroup = ref('');//账号用户组
const MyId = ref('');//账号id
function inutSelect() {
  //console.log(selectedUserGroup.value);//成功获取
};

//编辑效果
function handleEdit(id: any) {
  msgTwo.value = !msgTwo.value;
  //console.log(id);
  MyId.value = id;
  const index = tableData.value.findIndex((item) => item.id === id)
  console.log(index);

  inputName.value = tableData.value[index].account;
  selectedUserGroup.value = tableData.value[index].userGroup;
}

//修改账号效果
const handleFinsihEdit = async () => {
  //格式书写
  interface IUserInfo {
    id: any,
    account: string,
    userGroup: string,
  }

  //登录效果,成功登录就本地存储账号的信息
  const userInfo = ref<IUserInfo>({
    id: MyId.value,
    account: inputName.value,
    userGroup: selectedUserGroup.value,
  })
  const res = await fetchLoginEighten(userInfo.value);
  console.log(res);
  msgTwo.value = !msgTwo.value;
  location.reload();
}

//编辑关闭效果
function handleClose() {
  msgTwo.value = !msgTwo.value;
}

//单个删除
const openOne = (id: any) => {
  ElMessageBox.confirm(
    '是否要删除该用户?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      const res = await fetchLoginNineteen({ id: id });
      //console.log(res);
      location.reload();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败',
      })
    })
}

//勾选状态
const msg = ref([]);

//翻页效果
const msgTwo = ref(false);
const currentPage = ref(1);//这是可以控制页数从哪一页开始
const pageSize = ref(5);
const size = ref<ComponentSize>('default');

const currentOrders = computed(() => {
  return tableData.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
})

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}

//日期转换
function formatDateTime(dateTimeStr: any) {
  const date = new Date(dateTimeStr);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  //
  const offsetHours = 8; // UTC+8
  const localHours = date.getUTCHours() + offsetHours;
  return `${year}-${month}-${day} ${localHours}:${minutes}:${seconds}`;
}

//获取账号列表数据
onMounted(async () => {
  const res = await fetchLoginSixteen({ currentPage: 1, pageSize: 9999 });
  console.log(res.data.data);

  const data = res.data.data.map((item: any) => {
    //切换字段
    if (item.ctime) {
      item.ctime = formatDateTime(item.ctime);
    }
    return item;
  });
  tableData.value = data;
})

//账号列表
const tableData = ref([]);

//通过@select-change监听勾选的变化并得到被勾选的id组成的数组并转为字符串
const handleSelectionChange = (val: any) => {
  console.log(val);
  msg.value = val;
  //console.log(msg.value[0].id);
  const id = JSON.stringify(msg.value.map((item) => item.id))
  console.log(id);//[76, 75, 73] -- string
  delArray.value = id;
}

//批量删除
const delArray = ref('');
const openTwo = (id: any) => {
  ElMessageBox.confirm(
    '是否要删除选中的所有用户?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      if (msg.value.length > 0) {
        ElMessage({
          type: 'success',
          message: '批量删除成功',
        })
        //console.log(delArray.value);
        const res = await fetchLoginSeventeen({ ids: delArray.value });
        //console.log(res);
        location.reload();
      } else {
        alert('没有勾选可删除的用户');
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '批量删除失败',
      })
    })
}

//取消全部选择
function handleCanle() {
  //console.log(msg.value);
  if (msg.value.length > 0) {
    location.reload();
  }
}
</script>

<style scoped>
.box {
  width: 85vw;
  margin-left: 1vw;
  box-shadow: 0.1vw 0.1vw 0.1vw 0.1vw #f0f0f0;
}

.box_header {
  padding: 1vw;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #f0f0f0;
}

.box_body {
  padding: 1vw;
}

.edit_box {
  width: 50vw;
  height: 16vw;
  padding: 1vw;
  border: 1px solid black;
  position: absolute;
  top: 10vw;
  left: 30vw;
  z-index: 9999;
  background-color: #fff;

  >.edit_box_header {
    display: flex;
    justify-content: space-between;
  }

  >.edit_box_body {
    height: 10vw;

    >div {
      padding: 1vw;

      >.selectBox {
        outline: none;
      }
    }
  }

  >.edit_box_foot {
    height: 5vw;
    display: flex;
    justify-content: right;
  }
}

.selectBox {
  width: 20vw;
  height: 2vw;
  border: 0.1vw solid #b7b1b1;
}

.edit_box_foot_btn_box {
  width: 12vw;
  height: 3vw;

  >.btn {
    width: 5vw;
  }
}

.mask {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 8888;
  background-color: gray;
  opacity: 0.5;
}

.close {
  cursor: pointer;
}

.pageBox {
  padding: 1vw;
}
</style>